package com.jibei.mendo.utils;

import android.graphics.Color;
import android.os.Debug;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.jibei.mendo.event.Event;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketImpl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by lhl on 2019/12/7.
 */
public class ServerUtil {

    private ServerSocket serverSocket;
    private Socket tempClientSocket;
    private Thread serverThread = null;
    public String read;
    private Handler handler;
    private static final int maxClientsCount = 10;
    private static final CommunicationThread[] threads = new CommunicationThread[maxClientsCount];

    private ServerUtil() {
        handler = new Handler();
    }

    public static ServerUtil getInstance() {
        return ServerUtil.Holder.instance;
    }

    private static class Holder {
        private static final ServerUtil instance = new ServerUtil();
    }

    public void startServer() {
        showMessage("Server Started.", Color.BLACK, false);
        ToastUtils.showShort("服务端开启成功");

        this.serverThread = new Thread(new ServerThread());
        this.serverThread.start();
    }

    public void sendServerMessage(String msg) {
        if (TextUtils.isEmpty(msg))
            return;
        showMessage("Server : " + msg, Color.BLUE, false);
        if (msg.length() > 0) {
            sendMessage(msg);
        }
    }

    public void showMessage(final String message, final int color, final Boolean value) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                LogUtils.d("lhl", "ServerUtil   >>>" + message + "\n" + color + "\n" + value);
            }
        });
    }

    //method implemented to send message to the client
    private void sendMessage(final String message) {
        try {
            if (null != tempClientSocket) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PrintWriter out = null;
                        try {
                            out = new PrintWriter(new BufferedWriter(
                                    new OutputStreamWriter(tempClientSocket.getOutputStream())),
                                    true);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        out.println(message);
                    }
                }).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String messageStr="Fire";
    private void sendMessage(final String message, String server_ip) {
        try {
            DatagramSocket s = new DatagramSocket();
            InetAddress local = InetAddress.getByName(server_ip);//"192.168.1.100");//my broadcast ip
            int msg_length = message.length();
            byte[] message_d = message.getBytes();
            DatagramPacket p = new DatagramPacket(message_d, msg_length, local, Constant.SERVER_PORT);
            s.send(p);
            Log.d("rockman", "message send");
        } catch (Exception e) {
            Log.d("rockman", "error" + e.toString());
        }
    }
    /* serverthread method implemented here to activate the server network */
    class ServerThread implements Runnable {

        public void run() {
            Socket socket;
            try {
                if (serverSocket == null) {
                    serverSocket = new ServerSocket(Constant.SERVER_PORT);
                }

            } catch (IOException e) {
                e.printStackTrace();
                showMessage("Error Starting Server : " + e.getMessage(), Color.RED, false);
                ToastUtils.showShort("启动服务器失败");
            }

            //communicates to client and displays error if communication fails
            if (null != serverSocket) {
//                while (!Thread.currentThread().isInterrupted()) {
                while (true) {
                    try {
                        socket = serverSocket.accept();
                        int i = 0;
                        for (i = 0; i < maxClientsCount; i++) {
                            if (threads[i] == null) {
                                //(threads[i] = new clientThread(clientSocket, threads)).start();
                                ///(threads[i] = new CommunicationThread(serverSocket, threads)).start();
//                                CommunicationThread commThread = new CommunicationThread(socket);
//                                new Thread(commThread).start();
                                threads[i]  = new CommunicationThread(socket);
                                new Thread(threads[i]).start();
                                break;
                            }
                        }
                        if (i == maxClientsCount) {
                            PrintStream os = new PrintStream(socket.getOutputStream());
                            os.println("Server too busy. Try later.");
                            Log.d("LY","Server too busy. Try later.");
                            os.close();
                            socket.close();
                        }
//                        CommunicationThread commThread = new CommunicationThread(socket);
//                        new Thread(commThread).start();
                    } catch (IOException e) {
                        e.printStackTrace();
                        showMessage("Error Communicating to Client :" + e.getMessage(), Color.RED, false);
                        ToastUtils.showShort("与客户端通讯失败");
                    }
                }
            }
        }
    }

    /* communicationThread class that implements the runnable class to communicate with the client */
    class CommunicationThread implements Runnable {

        private Socket clientSocket;

        private BufferedReader input;

        public CommunicationThread(Socket clientSocket) {
            this.clientSocket = clientSocket;
            tempClientSocket = clientSocket;
            SocketAddress remotAddress =  tempClientSocket.getRemoteSocketAddress();
            Log.d("LY",remotAddress.toString());
            try {
                this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
            } catch (IOException e) {
                e.printStackTrace();
                showMessage("Error Connecting to Client!!", Color.RED, false);
                ToastUtils.showShort("客户端连接失败");
            }
            showMessage("Connected to Client!!", 0, true);
            ToastUtils.showShort("与客户端通讯成功");
            EventBusUtil.getInstance().postEvent(new Event(Constant.Events.SERVER2CLIENTSUCCESS,true));
        }

        public void run() {

//            while (!Thread.currentThread().isInterrupted()) {
            while (true) {
                try {
                    //checks to see if the client is still connected and displays disconnected if disconnected
                    read = input.readLine();
                    if (null == read || "Disconnect".contentEquals(read)) {
                        Thread.interrupted();
                        read = "Offline....";
                        showMessage("Client : " + read, 0, true);
                        ToastUtils.showShort(read);
                        break;
                    }
                    showMessage("Client : " + read, 0, true);
                    ToastUtils.showShort(read);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }

    //getTime method implemented to format the date into H:m:s
    private String getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
        return sdf.format(new Date());
    }

    //personally described onDestroy method to disconnect from the network on destroy of the activity
    public void disconnectServer() {
        if (null != serverThread) {
            sendMessage("Disconnect");
            serverThread.interrupt();
            serverThread = null;
        }
    }
}
